<template>
  <div>
    <h3>日常训练数据录入</h3>
    <div class="top">
      <el-row type="flex" :gutter="20">
        <el-col :span="6" :style="!tableShow?'':{pointerEvents: 'none'}">
          <el-card shadow="never" class="box-card">
            <div slot="header" class="clearfix">
              <span>运动员</span>
              <el-button @click="addPlayerModal=true" style="float: right; padding: 0" type="text" icon="el-icon-setting">管理运动员
              </el-button>
            </div>
            <div class="card-body">
              <el-alert @close="playerClose(index)" v-for="(item,index) in currentPlayerData" :key="item" class="text item" :title="dict_player[item]">
                <div class="up-btn">
                  <i @click="sortMove('up',index,currentPlayerData)" class="el-icon-top"></i>
                  <i @click="sortMove('down',index,currentPlayerData)" class="el-icon-bottom"></i>
                  <i @click="sortMove('top',index,currentPlayerData)" class="el-icon-download" style="transform: rotate(180deg);"></i>
                  <i @click="sortMove('bottom',index,currentPlayerData)" class="el-icon-download"></i>
                </div>
              </el-alert>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6" :style="!tableShow?'':{pointerEvents: 'none'}">
          <el-card shadow="never" class="box-card">
            <div slot="header" class="clearfix">
              <span>指标</span>
              <el-button @click="addMetaModal=true" style="float: right; padding: 0" type="text" icon="el-icon-setting">管理指标
              </el-button>
            </div>
            <div class="card-body">
              <el-alert @close="metaClose(index)" v-for="(item,index) in currentMetaData" :key="item" class="text item" :title="dict_meta[item]">
                <div class="up-btn">
                  <i @click="sortMove('up',index,currentMetaData)" class="el-icon-top"></i>
                  <i @click="sortMove('down',index,currentMetaData)" class="el-icon-bottom"></i>
                  <i @click="sortMove('top',index,currentMetaData)" class="el-icon-download" style="transform: rotate(180deg);"></i>
                  <i @click="sortMove('bottom',index,currentMetaData)" class="el-icon-download"></i>
                </div>
              </el-alert>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6" :style="!tableShow?'':{pointerEvents: 'none'}">
          <el-card shadow="never" class="box-card">
            <div slot="header" class="clearfix">
              <span>快捷操作</span>
            </div>
            <div class="card-body btn">
              <el-button @click="importLatest" type="primary" size="small" plain>从上次导入</el-button>
              <el-button @click="myTemplateShow=true" type="primary" size="small" plain>从模板导入</el-button>
              <el-button @click="templateEvent" type="primary" size="small" plain>保存为模板</el-button>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="never" class="box-card">
            <div slot="header" class="clearfix">
              <span>开始录入</span>
            </div>
            <div class="card-body" style="position: relative;">
              <div class="block" :style="!tableShow?'':{pointerEvents: 'none'}">
                <span class="demonstration">录入日期</span>
                <el-date-picker v-model="createDate" type="datetime" placeholder="选择日期时间" align="right"
                  :picker-options="pickerOptions">
                </el-date-picker>
              </div>
              <div style="position: absolute;bottom: 0;right: 0;">
                <el-button @click="submit" type="primary" icon="el-icon-setting" :loading="loading" :disabled="tableShow">开始录入</el-button>
                <el-button @click="tableShow=false" type="warning" >清空</el-button>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>
    <div class="table" v-if="tableShow">
      <el-card shadow="never" class="box-card">
        <div slot="header" class="clearfix">
          <span>录入日期 {{$moment(createDate).format('YYYY-MM-DD HH:mm:ss')}}</span>
        </div>
        <div class="" style="position: relative;">
          <el-table :data="tableData" style="width: 100%" max-height="800">
            <el-table-column fixed prop="player" label="姓名" width="100">
              <template slot-scope="scope">
                <span>{{dict_player[scope.row['player']]}}</span>
              </template>
            </el-table-column>
            <el-table-column v-for="item,index in tableHeader" :key="index" :label="dict_meta[item]" width="150" align="center">
              <template slot-scope="scope">
                <el-input v-model="scope.row[item]" size="small" :disabled="disabledIndex.indexOf(scope.$index)>-1"></el-input>
              </template>
            </el-table-column>
            <el-table-column fixed="right" prop="" label="操作" width="60">
              <template slot-scope="scope">
                <el-button @click="save(scope.row,scope.$index)" size="small" type="primary" icon="iconfont icon-save" :disabled="disabledIndex.indexOf(scope.$index)>-1" circle></el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-card>
    </div>
    <vxe-modal v-model="addPlayerModal" title="运动员管理" width="630" height="420" show-footer>
      <template #default>
        <el-transfer v-model="currentPlayerData" :data="allPlayerData" :titles="['未添加','已添加']" filterable
          :filter-method="filterMethod" filter-placeholder="快捷检索" target-order="push"></el-transfer>
      </template>
      <template #footer>
        <el-button @click="addPlayerEvent" type="primary" icon="" size="mini">确定</el-button>
      </template>
    </vxe-modal>
    <vxe-modal v-model="addMetaModal" title="指标管理" width="630" height="420" show-footer>
      <template #default>
        <el-transfer v-model="currentMetaData" :data="allMetaData" :titles="['未添加','已添加']" filterable
          :filter-method="filterMethod" filter-placeholder="快捷检索" target-order="push"></el-transfer>
      </template>
      <template #footer>
        <el-button @click="addMetaEvent" type="primary" icon="" size="mini">确定</el-button>
      </template>
    </vxe-modal>
    <vxe-modal v-model="templateShow" title="保存为模板" width="400" show-footer>
      <template #default>
        模板名称<el-input v-model="templateName" placeholder="自定义模板名称" @input="templateInputChange" clearable></el-input>
      </template>
      <template #footer>
        <el-button @click="templateShow=false" type="warning" size="mini">取消</el-button>
        <el-button v-if="!nameRepeat" @click="templateSave" type="primary" size="mini">保存</el-button>
        <el-popconfirm v-else title="您有相同模板名称确定要使用吗？" @onConfirm="templateSave">
          <el-button style="margin-left: 10px;" type="primary" slot="reference" size="mini">保存</el-button>
        </el-popconfirm>
      </template>
    </vxe-modal>
    <vxe-modal v-model="myTemplateShow" title="我的模板" width="400" height="600" show-footer>
      <template #default>
        <playerMetaTemplate ref="playerMetaTemplate" :templateData="templateData" />
      </template>
      <template #footer>
        <el-button @click="myTemplateShow=false" type="warning" size="mini">取消</el-button>
        <el-button @click="checkedTemplate" type="primary" icon="" size="mini">确定</el-button>
      </template>
    </vxe-modal>
  </div>
</template>

<script>
  import {
    currentRolePlayer
  } from '@/api/person.js'
  import {
    meta_all,
    insert4DailyTraining,
    userTemplateInsert,
    userTemplateSelect,
    importFromLatest
  } from '@/api/meta.js'
  import playerMetaTemplate from '@/components/meta/playerMetaTemplate.vue'
  export default {
    components: {playerMetaTemplate},
    data() {
      return {
        addPlayerModal: false,
        addMetaModal: false,
        allPlayerData: [],
        allMetaData: [],
        currentPlayerData: [],
        currentMetaData: [],
        playerData: [],
        metaData: [],
        dict_player: {},
        dict_meta: {},
        filterMethod(query, item) {
          return item.label.indexOf(query) > -1;
        },
        createDate: new Date(),
        pickerOptions: {
          shortcuts: [{
              text: '今天',
              onClick(picker) {
                picker.$emit('pick', new Date());
              }
            }, {
              text: '昨天',
              onClick(picker) {
                const date = new Date();
                date.setTime(date.getTime() - 3600 * 1000 * 24);
                picker.$emit('pick', date);
              }
            }, {
              text: '一周前',
              onClick(picker) {
                const date = new Date();
                date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
                picker.$emit('pick', date);
              }
            },
            {
              text: '一月前',
              onClick(picker) {
                const date = new Date();
                date.setTime(date.getTime() - 3600 * 1000 * 24 * 30);
                picker.$emit('pick', date);
              }
            }
          ]
        },
        tableHeader: [],
        tableData: [],
        tableShow: false,
        loading: false,
        disabledIndex: [],
        templateShow: false,
        templateName: '',
        templateData: [],
        nameRepeat: false,
        myTemplateShow: false,
      }
    },
    created() {
      this.getPlayer()
      this.getMeta()
      this.getTemplate()
    },
    watch:{
      createDate(val) {
        if(!val){
          this.createDate = new Date()
        }
      },
    },
    methods: {
      sortMove(e,index,data) {
        if(e=='up'){
          if(index!=0){
            data[index] = data.splice(index-1, 1, data[index])[0]
          }
        }else if(e=='down') {
          if(index!=data.length-1){
            data[index] = data.splice(index+1, 1, data[index])[0]
          }
        }else if(e=='top') {
          let item = data.splice(index,1)
          data.unshift(item[0])
        }else if(e=='bottom') {
          let item = data.splice(index,1)
          data.push(item[0])
        }
      },
      importLatest() {
        importFromLatest({usage:'日常训练'}).then(res=>{
          if(res.code === 200) {
            this.useTtemplate(res.data)
          }
        })
      },
      checkedTemplate() {
        let selectedTemplate = this.$refs.playerMetaTemplate.templateRadio
        this.useTtemplate(selectedTemplate)
        this.myTemplateShow = false
      },
      useTtemplate(data) {
        this.currentPlayerData = data.playerIdInfo.split(',').map(Number)
        this.currentMetaData = data.metaIdInfo.split(',').map(Number)
      },
      getTemplate() {
        userTemplateSelect().then(res=>{
          if(res.code === 200 && res.data.length!=0) {
            this.templateData = res.data.reverse()
          }else{
            this.templateData = []
          }
        })
      },
      templateInputChange() {
        this.nameRepeat = false
        this.templateData.forEach(item=>{
          if(item.name == this.templateName){
            this.nameRepeat = true
          }
        })
      },
      templateSave() {
        if(!this.templateName){
          this.$message.warning('请输入模板名称')
          return
        }
        let data = {
          name: this.templateName,
          usage: '日常训练',
          playerIdInfo: this.currentPlayerData.join(','),
          metaIdInfo: this.currentMetaData.join(',')
        }
        userTemplateInsert(data).then(res=>{
          if(res.code === 200) {
            this.templateData.unshift(res.data)
            this.$message.success('模板保存成功！')
            this.templateShow = false
          }else{
            this.$message.error('保存失败！')
          }
        })
      },
      templateEvent() {
        this.templateName = '我的模板'+(this.templateData.length+1)
        this.nameRepeat = false
        this.templateShow = true
      },
      save(row,index) {
        let data = []
        for(let key in row){
          if(key != 'player'){
            let obj = {}
            obj['playerId'] = row.player
            obj['metaId'] = key
            obj['valueDisplay'] = row[key]
            data.push(obj)
          }
        }
        insert4DailyTraining({metaDataSimples:data,createDate:this.$moment(this.createDate).format('YYYY-MM-DD HH:mm:ss')}).then(res=>{
          if(res.code === 200){
            this.disabledIndex.push(index)
            this.$message.success('保存成功！')
          }else{
            this.$message.error('保存失败！')
          }
        })
      },
      submit() {
        this.loading = true
        this.tableHeader = this.currentMetaData
        this.tableData = []
        let metaObj = {}
        this.currentMetaData.forEach(meta => {
          metaObj[meta] = ''
        })
        this.currentPlayerData.forEach(player => {
          let obj = {}
          Object.assign(obj, metaObj)
          obj['player'] = player,
            this.tableData.push(obj)
        })
        this.disabledIndex = []
        let timer = setTimeout(()=>{
          this.tableShow = true
          this.loading = false
          clearTimeout(timer)
        },200)
      },
      addMetaEvent() {
        this.addMetaModal = false
      },
      addPlayerEvent() {
        this.addPlayerModal = false
      },
      addMeta() {
        this.allMetaData = []
        this.metaData.forEach(item => {
          this.allMetaData.push({
            key: item.metaId,
            label: item.name,
          })
        })
      },
      addPlayer() {
        this.allPlayerData = []
        this.playerData.forEach(item => {
          this.allPlayerData.push({
            key: item.playerId,
            label: item.name,
          })
        })
      },
      metaClose(index) {
        this.currentMetaData.splice(index, 1)
      },
      playerClose(index) {
        this.currentPlayerData.splice(index, 1)
      },
      getPlayer() {
        currentRolePlayer().then(res => {
          if (res.code === 200 && res.data.length != 0) {
            this.playerData = res.data
            let dict = {}
            res.data.forEach(item => {
              this.currentPlayerData.push(item.playerId)
              dict[item.playerId] = item.name
            })
            this.dict_player = dict
            this.addPlayer()
          } else {
            this.playerData = []
          }
        })
      },
      getMeta() {
        meta_all().then(res => {
          if (res.code === 200 && res.data.length != 0) {
            res.data = res.data.reverse()
            this.metaData = res.data
            let dict = {}
            res.data.forEach((item, index) => {
              dict[item.metaId] = item.name
            })
            for (let i = 0; i < 10; i++) {
              this.currentMetaData.push(res.data[i].metaId)
            }
            this.dict_meta = dict
            this.addMeta()
          } else {
            this.metaData = []
          }
        })
      },
    }
  }
</script>

<style lang="scss">
  .box-card {
    .card-body {
      height: 300px;
      overflow: auto;
      padding: 0 10px;

      .item {
        margin: 5px 0;
        color: #000000;

        &:hover {
          background-color: #d8d8d8;
        }
      }
      .up-btn{
        width: 200px;
        height: 40px;
        display: flex;
        align-items: center;
        justify-content: center;
        position: absolute;
        top: 0;
        right: 0;
        i{
          margin: 0 10px;
          cursor: pointer;
          font-size: 120%;
          &:hover{
            color: #000000;
          }
        }
      }
    }

    .btn {
      width: 100%;
      display: flex;
      flex-direction: column;
      align-items: center;

      .el-button {
        width: 70%;
        margin: 10px 0;
      }
    }

    .card-body::-webkit-scrollbar {
      /*滚动条整体样式*/

      width: 10px;
      /*高宽分别对应横竖滚动条的尺寸*/
      height: 1px;
    }
    .card-body::-webkit-scrollbar-thumb {
      /*滚动条里面小方块*/

      border-radius: 10px;
      -webkit-box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
      background: #0DA883;

    }

    .card-body::-webkit-scrollbar-track {
      /*滚动条里面轨道*/
      -webkit-box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
      border-radius: 10px;
      background: #EDEDED;

    }
  }
  .table{
    margin-top: 20px;
  }
</style>
